package com.factory.test.m5622;

import android.os.Bundle;
import android.view.View;
import android.widget.ScrollView;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;

import com.factory.test.R;
import com.factory.test.base.BaseTestActivity;
import com.factory.test.databinding.ActivityM5622Rs485Binding;
import com.factory.test.util.DataConversion;
import com.yecontech.sdk.base.io.IOCallBack;
import com.yecontech.sdk.base.io.RS485Manager;


/**
 * RS485测试
 */
public class RS485Activity extends BaseTestActivity {

    private ActivityM5622Rs485Binding binding;
    private RS485Manager rs485Manager;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_m5622_rs485);


        rs485Manager = sdkService.getRS485Manager();
        rs485Manager.open("/dev/ttyS5", 9600, new IOCallBack() {
            @Override
            public void onReceiverData(byte[] by) {
                appendMessage(DataConversion.toHexString(by, by.length));
            }
        });

        binding.send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String s = binding.input.getText().toString();

                if(isEmpty(s)){
                    showWarning("请输入16进制数据");
                    return;
                }

                if(s.length() % 2 != 0){
                    showError("仅支持收发16进制");
                    return;
                }

                byte[] by = DataConversion.toByteArray(s);
                rs485Manager.send(by);
            }
        });

        binding.clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.textView.setText("");
            }
        });
    }



    public void appendMessage(String s){
        handler.post(new Runnable() {
            @Override
            public void run() {
                binding.textView.append(s);
                binding.textView.append("\n");
            }
        });

        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                binding.scrollView.fullScroll(ScrollView.FOCUS_DOWN);
            }
        }, 100);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        rs485Manager.close();
    }
}
